package com.allwees.bs.module.ics.service.impl;

import cn.hutool.core.lang.Assert;
import com.allwees.bs.module.base.service.impl.BoServiceImpl;
import com.allwees.bs.module.ics.dao.IcsChannelDao;
import com.allwees.bs.module.ics.dao.IcsNicheDao;
import com.allwees.bs.module.ics.dao.IcsPersonalChannelDao;
import com.allwees.bs.module.ics.dao.InternetCelebrityDao;
import com.allwees.bs.module.ics.entity.IcsChannel;
import com.allwees.bs.module.ics.entity.IcsNiche;
import com.allwees.bs.module.ics.entity.IcsPersonalChannel;
import com.allwees.bs.module.ics.entity.InternetCelebrity;
import com.allwees.bs.module.ics.req.IcsPersonalChannelReq;
import com.allwees.bs.module.ics.service.IcsPersonalChannelService;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Service
public class IcsPersonalChannelServiceImpl extends BoServiceImpl<IcsPersonalChannelDao, IcsPersonalChannel> implements IcsPersonalChannelService {

    @Autowired
    private IcsChannelDao icsChannelDao;
    @Autowired
    private IcsNicheDao icsNicheDao;
    @Autowired
    private InternetCelebrityDao internetCelebrityDao;

    @Override
    public void create(IcsPersonalChannelReq req) {
        validate(req);
        super.create(req);
    }

    @Override
    public void updateByUuid(IcsPersonalChannelReq req) {
        validate(req);
        super.updateByUuid(req);
    }

    private void validate(IcsPersonalChannelReq req) {
        InternetCelebrity internetCelebrity = internetCelebrityDao.findByUuid(req.getBo().getIcUuid());
        Assert.notNull(internetCelebrity, "网红不存在");

        IcsChannel channel = icsChannelDao.findByUuid(req.getBo().getIcUuid());
        Assert.notNull(channel, "渠道不存在");

        Set<String> nicheUuids = new HashSet(Collections.singletonList(req.getBo().getNicheUuids()));
        List<IcsNiche> niches = icsNicheDao.findByUuids(nicheUuids);
        Assert.isTrue(niches != null && niches.size() == nicheUuids.size(), "分类中有不存在的分类");

        req.getBo().setNichesStr(StringUtils.join(niches.stream().map(IcsNiche::getName).toArray(), ","));
    }
}
